package com.adminx.web.controller;
/*import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;*/

import com.adminx.po.User;
import com.adminx.service.RoleService;
import com.adminx.service.UserService;
import com.adminx.service.impl.UserServiceImpl;
import com.adminx.utils.ModelAndView;
import com.javaweb.common.DispatcherTool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/*
 * 用户控制类
 */
@WebServlet(urlPatterns = {"/adminx/login"})
public class UserController extends CommonController {

	private Logger logger = LogManager.getLogger(UserController.class) ;
	//依赖注入
	/*@Autowired */

	private UserService userService = new UserServiceImpl();

	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp) ;
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       login(req, resp) ;
    }
	public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object>  reqData = this.readRequestData(req, Map.class) ;
		String loginName = (String) reqData.get("username") ;
		String pwd = (String) reqData.get("pwd") ;
		HttpSession session = req.getSession() ;
        ModelAndView model = null ;
		//通过用户名和密码查询用户
		User user=userService.findUser(loginName, pwd);
		if(user != null){
			if (user.getStatus().equals("2")) {
				//用户被启用时，允许登录到后台
				session.setAttribute("login_user", user);
				model = ModelAndView.buildSuccess(resp) ;
                logger.debug("login successfully.") ;
				model.response();


			} else {
				//账号未启用或被禁用时，不允许登录到后台
				//model.addAttribute("msg", "账号未启用或被禁用，请联系管理员！");
				logger.debug("login failed.") ;
				model = ModelAndView.buildFailed(resp,"账号未启用或被禁用，请联系管理员！") ;
				model.response();

			}
		} else {
			//账号或密码错误时，不允许登录到后台
			logger.debug("login failed.") ;
            model = ModelAndView.buildFailed(resp,"账号或密码错误时，不允许登录到后台!") ;
            model.response();

		}
	}
	//退出登录

	public String logout(HttpSession session){
		//清空session
		session.invalidate();
		return "../../login";
	}
}
